package com.youpai.platform.order.job;

import com.youpai.platform.order.service.entity.po.OrderPO;
import com.youpai.platform.order.service.enums.OrderStatusEnum;
import com.youpai.platform.order.service.mapper.OrderMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


//@Component
//@EnableScheduling   // 1.开启定时任务
//@EnableAsync        // 2.开启多线程
public class UpdateOrderJob {

    @Resource
    private OrderMapper orderMapper;

    //定时关单 5分钟执行一次
    @Async
    @Scheduled(cron = "* 0/5 * * * ? *")
    public void updateOrderStatus() {
        //1.查询超过30分钟未进行处理的单子
        Timestamp threeTimes = getNow();
        List<OrderPO> orderPOS = orderMapper.getNoPayList(threeTimes, OrderStatusEnum.PAY_SUCCESS_FAILED.status);
        if(CollectionUtils.isEmpty(orderPOS)){
            System.out.println("暂无可更新订单");
        }else {
            List<Long> orderIds = orderPOS.stream().map(OrderPO::getOrderId).collect(Collectors.toList());
            Integer count = orderMapper.shutDownOrder(orderIds, OrderStatusEnum.CANCEL_ORDER_SUCCESS.status);
            if(count > 0){
                System.out.println("成功批量取消订单");
            }else {
                System.out.println("批量取消订单失败");
            }
        }
    }

    //定时退款任务 5分钟执行一次
    @Async
    @Scheduled(cron = "* 0/5 * * * ? *")
    public void refundOrders() {
        //查询30分钟以内需要退款的单子
        Timestamp threeTimes = getNow();
        List<OrderPO> orderPOS = orderMapper.getNoPayList(threeTimes, OrderStatusEnum.REFUND_ING.status);
        //调用退款方法
    }

    //获取30分钟前时间戳
    public static Timestamp getNow() {
        Long ThreeTimes = System.currentTimeMillis() - (1000 * 60 *30);
        return new Timestamp(ThreeTimes);
    }

}
